//
//  TimingPatternScheduleViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/23/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "TimingPatternScheduleViewController.h"

@interface TimingPatternScheduleViewController ()

@end

@implementation TimingPatternScheduleViewController

@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize index=_index;

@synthesize sections=_sections;
@synthesize beginTimeSection=_beginTimeSection;
@synthesize endTimeSection=_endTimeSection;
@synthesize beginTimePicker=_beginTimePicker;
@synthesize endTimePicker=_endTimePicker;
@synthesize publicSender=_publicSender;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if(!_beginTimeSection)
    {
        _beginTimeSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _beginTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_beginTimeSection.contents addObject:[[self.timingPattern.timeRangeList objectAtIndex:self.index] beginTime]];
        
        _beginTimeSection.header=@"Begin Time";
    }
    if(!_endTimeSection)
    {
        _endTimeSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _endTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_endTimeSection.contents addObject:[[self.timingPattern.timeRangeList objectAtIndex:self.index] endTime]];
        
        _endTimeSection.header=@"End Time";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:self.beginTimeSection];
        [_sections addObject:self.endTimeSection];
    }
    
    if (!_beginTimePicker) {
        _beginTimePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 250)];
        _beginTimePicker.datePickerMode = UIDatePickerModeTime;
        _beginTimePicker.hidden = YES;
        NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
        [inputFormat setDateFormat:@"yyyy-MM-dd HH:mm aa"];
        NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00 AM"];
        if (![self.agency.syncTime isEqualToString:@""]) {
            NSLog(@"2012-01-01 %@",self.agency.syncTime);
            inputDate = [inputFormat dateFromString: [NSString stringWithFormat:@"2012-01-01 %@",[[self.timingPattern.timeRangeList objectAtIndex:self.index] beginTime]]];
        }
        [_beginTimePicker setDate:inputDate];
        [self.view addSubview:_beginTimePicker];
    }
    
    if (!_endTimePicker) {
        _endTimePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 250)];
        _endTimePicker.datePickerMode = UIDatePickerModeTime;
        _endTimePicker.hidden = YES;
        NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
        [inputFormat setDateFormat:@"yyyy-MM-dd HH:mm aa"];
        NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00 AM"];
        if (![self.agency.syncTime isEqualToString:@""]) {
            NSLog(@"2012-01-01 %@",self.agency.syncTime);
            inputDate = [inputFormat dateFromString: [NSString stringWithFormat:@"2012-01-01 %@",[[self.timingPattern.timeRangeList objectAtIndex:self.index] endTime]]];
        }
        [_endTimePicker setDate:inputDate];
        [self.view addSubview:_endTimePicker];
    }
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.agency=nil;
    self.subSystem=nil;
    self.timingPattern=nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    cell.textLabel.text=sectionContentString;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 0:
        {
            [[self navigationController] setNavigationBarHidden:NO];
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectBeginTime:)];
            self.navigationItem.rightBarButtonItem = item;
            [item release];
            [self.editButtonItem setStyle:UIBarButtonItemStyleDone];
            [self.beginTimePicker setHidden:NO];
            self.title=@"Select Begin time";
            //            [_timePicker release];
        }
            break;
        case 1:
        {
            [[self navigationController] setNavigationBarHidden:NO];
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectEndTime:)];
            self.navigationItem.rightBarButtonItem = item;
            [item release];
            [self.editButtonItem setStyle:UIBarButtonItemStyleDone];
            [self.endTimePicker setHidden:NO];
            self.title=@"Select End time";
            //            [_timePicker release];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Customized functions
- (id) initWithNibNameAndTimingPattern:(NSString *)nibName timingPattern:(TimingPattern *)timingPattern subSystem:(SubSystem *)subSystem agency:(Agency *)agency index:(int)index bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    self.index=index;
    return self;
}

- (void) selectBeginTime:(id) sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeStyle=NSDateFormatterShortStyle;
    //	[[self.sections objectAtIndex:0] setContents:[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil]];
    TimeRange *timeRange=[self.timingPattern.timeRangeList objectAtIndex:self.index];
    [timeRange setBeginTime:[df stringFromDate:self.beginTimePicker.date]];
    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [df release];
    [self updateViewController];
    

    [self.beginTimePicker setHidden:YES];
    self.navigationItem.rightBarButtonItem=nil;
    self.navigationController.title=@"Time Schedule";
    //    [[self navigationController] setNavigationBarHidden:YES];

    
}

- (void) selectEndTime:(id) sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeStyle=NSDateFormatterShortStyle;
    //	[[self.sections objectAtIndex:0] setContents:[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil]];
    TimeRange *timeRange=[self.timingPattern.timeRangeList objectAtIndex:self.index];
    [timeRange setEndTime:[df stringFromDate:self.endTimePicker.date]];
    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [df release];
    [self updateViewController];
    
    
    [self.endTimePicker setHidden:YES];
    self.navigationItem.rightBarButtonItem=nil;
    self.navigationController.title=@"Time Schedule";
    //    [[self navigationController] setNavigationBarHidden:YES];
    
    
}

- (void) updateViewController
{
    if(self.beginTimeSection)
    {
        self.beginTimeSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        self.beginTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.beginTimeSection.contents addObject:[[self.timingPattern.timeRangeList objectAtIndex:self.index] beginTime]];
        
        self.beginTimeSection.header=@"Begin Time";
    }
    if(self.endTimeSection)
    {
        self.endTimeSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        self.endTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.endTimeSection.contents addObject:[[self.timingPattern.timeRangeList objectAtIndex:self.index] endTime]];
        
        self.endTimeSection.header=@"End Time";
    }
    if (self.sections) {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        [self.sections addObject:self.beginTimeSection];
        [self.sections addObject:self.endTimeSection];
    }
    [self.tableView reloadData];

}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
